package org.lazycoder.logger.module.ask3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.lazycoder.logger.Event;
import org.lazycoder.logger.EventLogger;
import org.lazycoder.logger.Module;

/**
 * @author Matthew Bayliss
 */
public class ASK3 extends Module {
	ScheduledExecutorService		sched;
	File							askDir;
	private final Vector<String>	files;
	LogObserver						observer;

	/**
         * 
         */
	public ASK3() {
		askDir = new File(System.getProperty("user.home")
				+ "/AppData/Roaming/.autopsy/dev/var/log/");
		files = new Vector<String>();
		if (askDir.exists()) {
			observer = new LogObserver(this);
			files.add("autopsy.log.0");
			files.add("autopsy_actions.log.0");
			// files.add("autopsy_traces.log.0");
			start();
		} else {
			Event event = new Event(
					"Error Starting ASK3 Module. Logging directory does not appear to exist. ",
					new Date());
			EventLogger.getInstance().update(this, event);
		}
	}

	@Override
	public String getName() {
		return "ASK3";
	}

	/**
	 * 
	 */
	public void start() {
		sched = Executors.newScheduledThreadPool(files.size());
		for (String file : files) {
			try {
				FileWatcher fw = new FileWatcher(askDir.getAbsolutePath()
						+ File.separator + file);
				fw.addObserver(observer);
				sched.scheduleAtFixedRate(fw, 100, 100, TimeUnit.MILLISECONDS);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				files.remove(file);
			}
		}
	}

	@Override
	public void stop() {
		sched.shutdown();
	}

	/**
	 * @param event
	 *            An event created by the LogObserver
	 */
	public void update(Event event) {
		if (event != null) {
			EventLogger.getInstance().update(this, event);
		}
	}
}